package com.fenfen.novel;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.fenfen.novel.utils.CommonUtil;
import com.fenfen.novel.utils.SharedPrefsUtils;

import java.util.ArrayList;

public class BaseActivity extends AppCompatActivity {

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean isNight = SharedPrefsUtils.getInstance(this).getChapterNightMode();
    int themeColorId = SharedPrefsUtils.getInstance(this).getThemeColor();
    int themeId = CommonUtil.getThemeId(isNight, themeColorId, this);
    changeTheme(themeId);
    MainApplication.getInstance().addActivity(this);
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    MainApplication.getInstance().removeActivity(this);
  }

  public void changeTheme(int themeId) {
    setTheme(themeId);
    boolean isFollowTheme = SharedPrefsUtils.getInstance(this).getNavigationColorMode();
    setNavigationColor(this, isFollowTheme);
  }

  public void setNavigationColor(BaseActivity context, boolean isFollowTheme) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      Log.d("Tag", "isFollowTheme=" + isFollowTheme);
      if (isFollowTheme) {
        int colorPrimaryDark = CommonUtil.resolveColor(this, R.attr.colorPrimaryDark);
        context.getWindow().setNavigationBarColor(colorPrimaryDark);
      } else {
        context.getWindow().setNavigationBarColor(ContextCompat.getColor(this, R.color.md_black_1000));
      }
    }
  }

  public void changeBrightness(boolean isNight, Context context) {
    int brightness = CommonUtil.NONE_INT_DATA;
    //get light and set
    try {
      brightness = CommonUtil.getCurrentLight(this);
    } catch (Settings.SettingNotFoundException e) {
      e.printStackTrace();
    }
    if (isNight && brightness > CommonUtil.CHAPTER_BRIGHTNESS_SHOW_DEFAULT) {
      brightness = CommonUtil.CHAPTER_BRIGHTNESS_SHOW_DEFAULT;
    }
    CommonUtil.changeAppBrightness(context, brightness);
  }

  public void notifyAllChangeTheme() {
    SharedPrefsUtils sp = SharedPrefsUtils.getInstance(this);
    boolean isNight = !sp.getChapterNightMode();
    sp.setChapterNightMode(isNight);
    ArrayList<BaseActivity> list = MainApplication.getInstance().getActivities();
    for (BaseActivity activity : list) {
//      changeTheme(isNight, colorName, activity);
      activity.recreate();
    }
  }

  public void notifyAllChangeNavigationColor(boolean isFollowTheme) {
    ArrayList<BaseActivity> list = MainApplication.getInstance().getActivities();
    for (BaseActivity activity : list) {
//      changeTheme(isNight, colorName, activity);
      setNavigationColor(activity, isFollowTheme);
    }
  }

}

